package com.dodol.util;

import com.dodol.common.FindElementBy;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class ElementFinder {


    /**
     * 定位元素
     *
     * @param driver
     * @param element
     * @return
     */
    public static WebElement findElement(WebDriver driver, Element element) {
        FindElementBy by = element.getFindElementBy();
        String elementPath = element.getValue();
        switch (by) {
            case ID:
                return driver.findElement(By.id(elementPath));
            case NAME:
                return driver.findElement(By.name(elementPath));
            case XPATH:
                return driver.findElement(By.xpath(elementPath));
            case LINKTEXT:
                return driver.findElement(By.linkText(elementPath));
            case CLASSNAME:
                //todo 这里查找出来的可能是一个元素集合，以后再处理
                return driver.findElement(By.className(elementPath));
            default:
                throw new NoSuchElementException("没有找到此元素！");
        }
    }


    /**
     * 获取元素text
     *
     * @param element
     * @return
     */
    public static String getElementText(WebElement element) {
        assert element != null;
        return element.getText();
    }

    /**
     * 获取元素尺寸
     *
     * @param element
     * @return
     */
    public static String getElementSize(WebElement element) {
        assert element != null;
        return element.getSize().toString();
    }

    /**
     * 获取元素的属性
     *
     * @param element
     * @param attrName
     * @return
     */
    public static String getElementAttribute(WebElement element, String attrName) {
        assert element != null;
        return element.getAttribute(attrName);
    }


    /**
     * 静态内部类element
     */
    public static class Element {
        private FindElementBy findElementBy;
        private String value;

        /**
         * 使用元素查找方式和查找参数可以描述一个元素的具体位置
         *
         * @param findElementBy
         * @param value
         */
        public Element(FindElementBy findElementBy, String value) {
            this.findElementBy = findElementBy;
            this.value = value;
        }


        public FindElementBy getFindElementBy() {
            return findElementBy;
        }

        public String getValue() {
            return value;
        }

        @Override
        public String toString() {
            return "查找方式：" + findElementBy.toString() + "查找参数：" + value;
        }
    }
}
